<?php
/**
 * 自定义工具包
 * 
 */
class UtilHelper
{
	public function init()
	{
		
	}
	
	public function js($js_files, $base_url = false)
	{
	    if (!is_array($js_files)) {
	        $js_files = array($js_files);
	    }
	    if ($base_url === false) {
	        $base_url = $this->get_base_url();
	    }
	    
	    foreach ($js_files as $js_file) {
	        echo '<script type="text/javascript" src="'. $base_url . $js_file .'?'. JS_VERSION .'"></script>' . PHP_EOL;
	    }
	}
	
	public function css($css_files, $base_url = false)
	{
	    if (!is_array($css_files)) {
	        $css_files = array($css_files);
	    }
	    if ($base_url === false) {
	        $base_url = $this->get_base_url();
	    }
	    
		foreach ($css_files as $css_file)
		{
			echo '<link rel="stylesheet" type="text/css" href="'. $base_url . $css_file .'?'. CSS_VERSION .'" />' . PHP_EOL;
		}
	}
	
	public function image($url, $base_url = false)
	{
	    if ($base_url === false) {
	        $base_url = $this->get_base_url();
	    }
	    echo $base_url . $url;
	}
	
	public function get_base_url()
	{
	    if (!empty(Yii::app()->theme->name)) {
	        return Yii::app()->theme->baseUrl . '/';
	    }
	    return BASE_URL;
	}
	
	public function sub_string($str, $start=0, $length=null, $charset="utf-8") 
	{
		if(function_exists("mb_substr")) {
			$length = empty($length) ? mb_strlen($str, $charset) : $length;
			if(mb_strlen($str,$charset) <= $length) {
				return $str;
			}
			$slice = mb_substr($str, $start, $length, $charset);
		} else {
			$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
			$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
			$re['gbk']	= "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
			$re['big5']	= "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
			preg_match_all($re[$charset], $str, $match);
			$length = is_null($length) ? count($match[0]) : $length;
			if(count($match[0]) <= $length) {
				return $str;
			}
			$slice = implode("", array_slice($match[0], $start, $length));
		}
		return $slice;
	}
	
	public function show_404()
	{
		header("HTTP/1.1 404 Not Found");
		exit('404 Not Found');
		Yii::app()->controller->renderFile(Yii::app()->viewPath . '/errors/404.php');
		die;
	}
	
	public function return_json($msg = '', $status = true, $url = '')
	{
		echo json_encode(array(
			'msg' => $msg,
			'status' => $status,
			'url' => $url
		));
		die;
	}
	
	public function str_format($str)
	{
		//return str_replace(array(chr(32),chr(13).chr(10)),array('&nbsp;','<br />'),$str);
		return nl2br(str_replace(chr(32),'&nbsp;',$str));
	}
	
	function html($item, $value = '', $html_options = array(), $template = '', $output = true)
	{
		$html = '';
		if (!empty($value)) {
			$item['value'] = $item['selected'] = $item['checked']  = $value;
		}
		if (!empty($item['html'])) {
			if (!empty($template)) {
				$html = sprintf($template, $item['html']).PHP_EOL;
			} else {
				$html = $item['html'].PHP_EOL;
			}
		} else {
			switch ($item['type']) {
				case 'textarea':
					foreach ($item as $attr => $value) {
						if (in_array($attr, array('text', 'template', 'value'))) {
							continue;
						}
						$fields[] = $attr . '="'.$value.'"';
					}
					$val = !empty($item['value']) ? $item['value'] : '';
					$html .= '<textarea '.implode(' ', $fields).'>' . $val . '</textarea>';
					if (!empty($item['template'])) {
						$html = sprintf($item['template'], $html);
					}
					if (!empty($template)) {
						$html = sprintf($template, $html);
					} else {
						$html = $html;
					}
					$html .= PHP_EOL;
					break;
				case 'radio':
				case 'checkbox':
					foreach ($item as $attr => $value) {
						if (in_array($attr, array('text', 'template', 'checked', 'selected', 'value', 'data'))) {
							continue;
						}
						$fields[] = $attr . '="'.$value.'"';
					}
					if (!empty($item['data'])) {
						while ($option = each($item['data'])) {
							$checked = '';
							if (isset($item['checked'])) {
								if (is_array($item['checked']) && in_array($option[0], $item['checked'])) {
									$checked = 'checked="checked"';
								} elseif ($item['selected'] == $option[0]) {
									$checked = 'checked="checked"';
								}
							}
							$html .= '&nbsp;&nbsp;<input '.implode(' ', $fields).' value="'.$option[0].'" '.$checked.'>' . $option[1];
						}
					}
					if (!empty($item['template'])) {
						$html = sprintf($item['template'], $html);
					}
					if (!empty($template)) {
						$html = sprintf($template, $html);
					} else {
						$html = $html;
					}
					$html .=  PHP_EOL;
					break;
				case 'file':
				case 'password':
				case 'text':
					foreach ($item as $attr => $value) {
						if (in_array($attr, array('text', 'template'))) {
							continue;
						}
						$fields[] = $attr . '="'.$value.'"';
					}
					$html .= '<input '.implode(' ', $fields).' />';
					if (!empty($item['template'])) {
						$html = sprintf($item['template'], $html);
					}
					if (!empty($template)) {
						$html = sprintf($template, $html);
					} else {
						$html = $html;
					}
					$html .= PHP_EOL;
					break;
				case 'select':
					foreach ($item as $attr => $value) {
						if (in_array($attr, array('text', 'type', 'template', 'checked', 'selected', 'value', 'data'))) {
							continue;
						}
						$fields[] = $attr . '="'.$value.'"';
					}
					$html .= '<select '.implode(' ', $fields).'>';
					if (!empty($item['data'])) {
						while ($option = each($item['data'])) {
							$selected = '';
							if (isset($item['selected'])) {
								if (is_array($item['selected']) && in_array($option[0], $item['selected'])) {
									$selected = 'selected="selected"';
								} elseif ($item['selected'] == $option[0]) {
									$selected = 'selected="selected"';
								}
							}
							$html .= '<option value="'.$option[0].'" '.$selected.'>'.$option[1].'</option>';
						}
					}
					$html .= '</select>';
					if (!empty($item['template'])) {
						$html = sprintf($item['template'], $html);
					}
					if (!empty($template)) {
						$html = sprintf($template, $html);
					} else {
						$html = $html;
					}
					$html .= PHP_EOL;
					break;
			}
		}
		
		if (is_array($html_options)) {
            foreach ($html_options as $property => $value) {
                $html = str_replace($property . '="', $property . '="' . $value . ' ', $html);
            }
		}
	
		if ($output == true) {
			echo $html;
		} else {
			return $html;
		}
	}
	
	function o($item, $value, $template = '')
	{
		if (!empty($template)) {
			$html = sprintf($template, $item['text'], $value).PHP_EOL;
		} else {
			$html = $item['text'] . $value.PHP_EOL;
		}
		echo $html;
	}
	
	public function loadViewConfig($name, $scenario)
	{
		static $instance = null;
		if ($instance) {
			return $instance;
		}
		$class =  ucfirst($name) . 'View';
		Yii::import('application.config.views.' . $class);
		$instance = new $class($scenario);
		return $instance;
	}
	
	/**
	 * @deprecated
	 */
	public function loadForm($name, $items = array())
	{
	    $form_file = '/config/forms/' . $name . '.php';
	    if (!empty(Yii::app()->theme->name) && is_file(Yii::app()->theme->basePath . $form_file)) {
	        $form_file = Yii::app()->theme->basePath . $form_file;
	    } else {
	        $form_file = PROTECTED_PATH . $form_file;
	    }
	    
	    if (!is_file($form_file)) return false;
	    $form = require $form_file;
		
		$res = array();
		if (!empty($items)) {
		    foreach ($items as $item) {
		        $res[$item] = $form[$item];
		    }
		} else {
		    $res = $form;
		}
		return $res;
	}
}